<script setup>
import { useRouter } from "vue-router";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from '@/store/userStore';

const router = useRouter();
const userStore = useUserStore();
const username = ref("");
const password = ref("");
// 点击登录
import { loginFn } from "@/api/login";

// 登录页面中
const loginClick = () => {

  if (username.value.length < 1) {
    return ElMessage({
      type: "error",
      message: "账号长度不够",
    });
  }
  if (password.value.length < 1) {
    return ElMessage({
      type: "error",
      message: "密码长度不够",
    });
  }

  loginFn({
    username: username.value,
    password: password.value,
  })
    .then((res) => {
      console.log("接口返回的数据:", res); // 打印接口返回的数据
      if (res.code === 1) {
        ElMessage({
          type: "success",
          message: res.message,
        });
        
        // 更新全局状态
        userStore.login(res.data.userData);
        console.log(res.data.userData);
        
        // 根据用户角色跳转
        if (res.data.userData.role === "admin") {
          router.push("/");
        } else {
          router.push("/");
        }
      } else {
        ElMessage({
          type: "error",
          message: res.message || "登录失败",
        });
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        type: "error",
        message: "登录出错",
      });
    });
};

</script>

<template>
  <div class="login-container">
    <div class="form-wrap">
      <h2>登录页面</h2>
      <el-input v-model="username" placeholder="请输入账号" clearable></el-input>
      <el-input v-model="password" placeholder="请输入密码" type="password" show-password clearable @keyup.enter="loginClick"></el-input>
      <div class="form-btn">
        <el-button color="#4285f4" @click="loginClick">登录</el-button>
        <el-button color="#4CAF50">注册</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  height: 100%;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url(../../assets/img/bg.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;

  .form-wrap {
    height: 260px;
    width: 500px;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 10px;

    h2 {
      margin: 0;
      color: white;
      text-align: center;
      margin: 32px;
    }

    .el-input {
      padding: 0 40px;
      margin-bottom: 20px;
    }
  }

  .form-btn {
    padding: 0 20px;
    display: flex;
    justify-content: space-evenly;
  }
}
</style>
